package com.hugo.eduservice.SubjectExcelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hugo.eduservice.entity.EduSubject;
import com.hugo.eduservice.entity.excel.SubjectData;

import com.hugo.eduservice.service.EduSubjectService;
import com.hugo.serviceconfig.exceptionhandler.HugoException;


//不能交给spring 管理 需要自己要new 不能注入其他对象
public class SubjectExeclListener extends AnalysisEventListener<SubjectData> {
    //不能注入service mapper
    public EduSubjectService eduSubjectService;
    public SubjectExeclListener() {}
    public SubjectExeclListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }


    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new HugoException(20001,"文件数据为空");
        }
        //一行一行读取 每次读取两个值

        //一级分类的添加
        EduSubject oneSubject = this.eduOneSubject(subjectData.getOneSubjectName(),eduSubjectService);
        if (oneSubject == null ){
            //如果数据库中没有查到则表示
            oneSubject=new EduSubject();
            oneSubject.setParentId("0");
            oneSubject.setTitle(subjectData.getOneSubjectName());
            eduSubjectService.save(oneSubject);
        }
        //区一级分类的id值
        String pid = oneSubject.getId();
        //二级分类
        EduSubject twoSubject = this.eduTwoSubject(subjectData.getTwoSubjectName(),eduSubjectService,pid);
        if (twoSubject == null ){
            //如果数据库中没有查到则表示
            twoSubject=new EduSubject();
            twoSubject.setParentId(pid);
            twoSubject.setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(twoSubject);
        }


    }
    //判断一级分类有没有重复
    private EduSubject eduOneSubject(String name,EduSubjectService eduSubjectService){
        QueryWrapper<EduSubject> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(queryWrapper);
        return oneSubject;


    }

    //判断二级分类不能重复添加
    private EduSubject eduTwoSubject(String name,EduSubjectService eduSubjectService,String pid){
        QueryWrapper<EduSubject> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        EduSubject twoSubject = eduSubjectService.getOne(queryWrapper);
        return twoSubject;


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
